const tips = {
  1: '抱歉，您的网络不稳定'
}

class HTTP {

  //http 请求类
  request(params,noRefetch,isLogin=false) { // 为类添加方法
    var that = this
    var url = getApp().globalData.baseRestUrl + params.url;
    console.log(url)

    if (!params.method) {
      params.method = 'POST';
    }
    wx.request({
      url: url,
      data: params.data,
      method: params.method,
      header: {
        'content-type': 'application/json',
        'token':wx.getStorageSync("token")
      }, 
      success: function (res) {
        console.log(res)
        console.log(params)
        var code = res.statusCode.toString();
        if(code === 200 ){
          params.success && params.success(res.data)
        }else{
          if (code == '401') {
            if (!noRefetch) {
                that._getNewToken(params);
            }
        }
        params.success && params.success(res.data)
        
        }    
      },
      fail: function (err) { // 错误反馈
        console.log('http-err', err)
        let msg = err.errMsg;
        that._show_error(msg)
      }
    });
  }

  _getNewToken(param){
    var that = this
    wx.login({
      success(res) {
        console.log(res)
        console.log('login-eeeee', res)
        let code = res.code;
        if(res.code){
          // 存入登陆状态，传入code, rawData, signature, encryptData.
          wx.request({
            url: getApp().globalData.baseRestUrl + '/user/wxlogin',
            method: "POST",
            dataType: "json",
            data: {
              code,
              loginType:'relogin'
            },
            header: {
              'content-type': 'application/json',
            },
            success: (res) => {
              if( res.data.code === 200){
                wx.setStorageSync('token',res.data.data.token.access_token);
                that.request(param,true)
              }
            },
            fail: (err) => {
              console.log('error',err)
            }
          });
        }
      },
  

    });
  }


  _show_error(msg) {
    wx.showToast({
      title: msg,
      icon: 'none',
      duration: 1500
    })
  }

};

function getCurrentPageUrl(){
  var pages = getCurrentPages()    //获取加载的页面
  var currentPage = pages[pages.length-1]    //获取当前页面的对象
  var url = currentPage.route    //当前页面url
  return url
}

export { HTTP };
